package com.jiantong.admin.controller.management;


import com.jiantong.admin.dto.Breed_UserDto;
import com.jiantong.admin.dto.CityAreaDto;
import com.jiantong.admin.model.PagingMz;
import com.jiantong.user.model.*;
import com.jiantong.user.service.*;
import io.terminus.boot.rpc.common.annotation.RpcConsumer;
import io.terminus.common.model.Paging;
import io.terminus.common.model.Response;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * Created by ThinkPad on 2017/8/2.
 */

@Controller
@RequestMapping("/management/factory")
public class BreedfactoryController {
    @RpcConsumer
    private BreedFactoryReadService breedFactoryReadService;
    @RpcConsumer
    private UserReadService userReadService;
    @RpcConsumer
    private UserWriteService userWriteService;
    @RpcConsumer
    private UserProfileReadService userProfileReadService;
    @RpcConsumer
    private BreedFactoryWriteService breedFactoryWriteService;
    @RpcConsumer
    private AppUserRoleWriteService appUserRoleWriteService;
    @RpcConsumer
    private OrganizationWriteService organizationWriteService;
    @RpcConsumer
    private UserProfileWriteService userProfileWriteService;
    @RpcConsumer
    private OrganizationUserWriteService organizationUserWriteService;
    @RpcConsumer
    private AppUserRoleReadService appUserRoleReadService;
    @RpcConsumer
    private GovernmentUserDutyReadService governmentUserDutyReadService;
    @RpcConsumer
    private GovernmentUserDutyWriteService governmentUserDutyWriteService;

    @GetMapping("/show")
    public String factory(
            Model model, HttpServletRequest request, HttpServletResponse response) {


        Map map = getarea(response, request);
        model.addAttribute("userProfile", map.get("userProfile"));
        model.addAttribute("cityAreaDtoList", map.get("cityAreaDtoList"));
        List<BreedFactory> breedFactoryList = (List<BreedFactory>) map.get("breedFactorys");
        List<BreedFactory> breedFactoryList1 = new ArrayList<>();
        for (BreedFactory breedFactory : breedFactoryList) {
            if (breedFactory.getIsScale() == 1) {
                breedFactoryList1.add(breedFactory);
            }
        }
        model.addAttribute("breedFactoryList", breedFactoryList1);
        model.addAttribute("username", map.get("username"));
        return "management/breedFactoryManagement/BreedFactoryList";
    }

    @GetMapping("/showList")
    @ResponseBody
    public PagingMz<Breed_UserDto> showBreedFactory(@RequestParam(required = false) Integer page,
                                                    @RequestParam(required = false) Integer rows,
                                                    @RequestParam(required = false) String breedFactoryId,
                                                    @RequestParam(required = false) Integer isScale) {
        Map criteria = new HashMap();
        if (page == null) {
            page = 1;
        }
        if (rows == null) {
            rows = 20;
        }
        if (breedFactoryId == null) {
            criteria.put("breedFactoryIds", null);
        } else {
            List<Long> list1 = new ArrayList<>();
            String[] list = breedFactoryId.split(",");

            for (int i = 0; i < list.length; i++) {
                int id = Integer.parseInt(list[i]);
                Long id1 = Integer.toUnsignedLong(id);
                list1.add(id1);
            }
            criteria.put("ids", list1);
        }

        criteria.put("isScale", isScale);

        Paging paging = breedFactoryReadService.pagingRetail(page, rows, criteria).getResult();
        List<Breed_UserDto> resultList = new ArrayList<>();
        Long records = paging.getTotal();
        Long pagetotal = (records - 1) / rows + 1;
        for (BreedFactory breedFactory : (List<BreedFactory>) paging.getData()) {
            User user = (User) userReadService.findById(breedFactory.getUserId()).getResult();
            Breed_UserDto dto = new Breed_UserDto(breedFactory, user);
            resultList.add(dto);
        }
        return new PagingMz<>(pagetotal, records, page, resultList);
    }

    @RequestMapping("add1")
    @ResponseBody
    public int add1(@RequestParam String province1,
                    @RequestParam Long province,
                    @RequestParam String city1,
                    @RequestParam Long city,
                    @RequestParam String region1,
                    @RequestParam Long region,
                    @RequestParam String street1,
                    @RequestParam Long street,
                    @RequestParam String village1,
                    @RequestParam Long village,
                    @RequestParam Long userxiejian,
                    @RequestParam String userxiejianname,
                    @RequestParam String name,
                    @RequestParam String username,
                    @RequestParam String phone,
                    @RequestParam Integer breedType,
                    @RequestParam Integer stockQuantity,
                    @RequestParam String longitude,
                    @RequestParam String latitude,
                    @RequestParam String detail,
                    @RequestParam String password,
                    @RequestParam Integer isScale, HttpServletRequest request, HttpServletResponse response1) {
        if (isScale==-1){
            isScale=0;
        }
        Map map = getarea(response1, request);

        BreedFactory breedFactory = new BreedFactory();
        UserProfile userProfile = (UserProfile) map.get("userProfile");
        breedFactory.setProvince(province1);
        breedFactory.setProvinceId(province);
        breedFactory.setCity(city1);
        breedFactory.setCityId(city);
        breedFactory.setRegion(region1);
        breedFactory.setRegionId(region);
        breedFactory.setStreet(street1);
        breedFactory.setStreetId(street);
        breedFactory.setVillage(village1);
        breedFactory.setVillageId(village);
        breedFactory.setBreedType(breedType);
        breedFactory.setDetail(detail);
        breedFactory.setLatitude(latitude);
        breedFactory.setLongitude(longitude);
        breedFactory.setStockQuantity(stockQuantity);
        breedFactory.setName(name);
        breedFactory.setIsScale(isScale);
        breedFactory.setStatus(1);
        breedFactory.setStableNumber("0");
        User user = new User();
        user.setAreaLevel(5);
        user.setMobile(phone);
        user.setName(username);
        user.setType(2);
        user.setPassword(password);
        user.setStatus(1);
        // 新建厂主账号
        Response<Long> longResponse = userWriteService.create(user);

        if (longResponse.getResult() == null) {
            return -1;
        }
        Long userId = longResponse.getResult();
        UserProfile userProfile1 = new UserProfile();
        userProfile1.setGender(0);
        userProfile1.setUserId(userId);
        userProfile1.setRealName(username);
        userProfile1.setProvince(province1);
        userProfile1.setProvinceId(province.intValue());
        userProfile1.setCity(city1);
        userProfile1.setCityId(city.intValue());
        userProfile1.setRegion(region1);
        userProfile1.setRegionId(region.intValue());
        userProfile1.setStreet(street1);
        userProfile1.setStreetId(street.intValue());
        userProfile1.setVillage(village1);
        userProfile1.setVillageId(village.intValue());
        userProfileWriteService.create(userProfile1);

        AppUserRole appUserRole = new AppUserRole();
        if (isScale==1){
            appUserRole.setAppRole(1);
        }
        if (isScale==0){
            appUserRole.setAppRole(10);
        }
        appUserRole.setStatus(1);
        appUserRole.setUserId(userId);
        Long result = appUserRoleWriteService.createAppUserRole(appUserRole).getResult();
        breedFactory.setUserId(userId);
        //增加机构


        Organization organization = new Organization();
        organization.setStatus(1);
        organization.setType(1);
        organization.setUserId(userId);
        organization.setName(name);
        Long orgid = organizationWriteService.create(organization).getResult();

        if (orgid == null) {
            return -1;
        }
        breedFactory.setId(orgid);
        //新建养殖场
        Response<Long> response = breedFactoryWriteService.create(breedFactory);

        if (response.getResult() == null) {
            return -1;
        }


        OrganizationUser organizationUser = new OrganizationUser();
        organizationUser.setOrganizationName(breedFactory.getName());
        organizationUser.setOrganizationId(orgid);
        organizationUser.setOrganizationType(1);
        organizationUser.setUserId(userId);
        organizationUser.setRoleName("养殖户");
        organizationUser.setUserName(username);
        //增加机构用户
        Response<Long> longResponse2 = organizationUserWriteService.create1(organizationUser);

        if (longResponse2.getResult() == null) {
            return -1;
        }
        GovernmentUserDuty governmentUserDuty = new GovernmentUserDuty();
        governmentUserDuty.setUserId(userxiejian);
        governmentUserDuty.setUserName(userxiejianname);
        governmentUserDuty.setFactoryOrPointId(response.getResult());
        governmentUserDuty.setFactoryOrPointName(breedFactory.getName());
        governmentUserDuty.setFactoryOrPointType(3);
        governmentUserDuty.setUserAppRole(6);
        Response<Long> longResponse1 = governmentUserDutyWriteService.add(governmentUserDuty);
        if (longResponse1.getResult() == null) {
            return -1;
        }
        return 1;
    }

    @RequestMapping("update1")
    @ResponseBody
    public Boolean update(@RequestParam Long id,
                          @RequestParam String name,
                          @RequestParam String username,
                          @RequestParam String phone,
                          @RequestParam Integer breedType,
                          @RequestParam Integer stockQuantity,
                          @RequestParam String longitude,
                          @RequestParam String latitude,
                          @RequestParam String detail) {
        BreedFactory breedFactory = new BreedFactory();

        breedFactory.setId(id);
        breedFactory.setBreedType(breedType);
        breedFactory.setDetail(detail);
        breedFactory.setLatitude(latitude);
        breedFactory.setLongitude(longitude);
        breedFactory.setStockQuantity(stockQuantity);
        breedFactory.setName(name);
        Response<Boolean> booleanResponse = breedFactoryWriteService.update(breedFactory);
        return booleanResponse.getResult();
    }

    @GetMapping("/retail")
    public String retail(Model model, HttpServletRequest request, HttpServletResponse response) {


        Map map = getarea(response, request);
        model.addAttribute("userProfile", map.get("userProfile"));
        model.addAttribute("cityAreaDtoList", map.get("cityAreaDtoList"));
        List<BreedFactory> breedFactoryList = (List<BreedFactory>) map.get("breedFactorys");
        List<BreedFactory> breedFactoryList1 = new ArrayList<>();
        for (BreedFactory breedFactory : breedFactoryList) {
            if (breedFactory.getIsScale() == 0) {
                breedFactoryList1.add(breedFactory);
            }
        }
        model.addAttribute("breedFactoryList", breedFactoryList1);
        model.addAttribute("username", map.get("username"));
        return "management/breedFactoryManagement/BreedRetailList";

    }


    @RequestMapping("getvillage")
    @ResponseBody
    public List getvillage(HttpServletRequest request, HttpServletResponse response) {
        Map map = getarea(response, request);
        List<CityAreaDto> list = (List) map.get("cityAreaDtoList");

        return list.get(0).getRegions();

    }

    @ResponseBody
    @RequestMapping("/getxiejianyuan")
    public List<UserProfile> xiejianyuan(HttpServletRequest request, HttpServletResponse response1) {
        Map map = getarea(response1, request);
        UserProfile userProfile = (UserProfile) map.get("userProfile");
        List<Integer> integerList = new ArrayList<>();
        integerList.add(5);
        integerList.add(6);
        List<AppUserRole> appUserRoleList = appUserRoleReadService.pagingLawAppUserRoles(1, 100000, integerList).getResult().getData();
        List<Long> longList = new ArrayList<>();
        for (AppUserRole appUserRole : appUserRoleList) {
            longList.add(appUserRole.getUserId());
        }
        List<UserProfile> userProfileList = new ArrayList<>();
        List<UserProfile> userProfiles = userProfileReadService.findUserIds(longList).getResult();
        for (UserProfile userProfile1 : userProfiles) {
            if (userProfile1.getRegionId() == userProfile.getRegionId()) {
                userProfileList.add(userProfile1);
            }
        }
        return userProfileList;
    }

    @GetMapping("/select")
    public String select() {
        return "management/breedFactoryManagement/select";
    }

    @GetMapping("/update")
    public String update() {
        return "management/breedFactoryManagement/update";
    }

    @GetMapping("/add")
    public String add() {
        return "management/breedFactoryManagement/add";
    }

    /**
     * 停用管辖区域内指定的养殖场
     */
    @RequestMapping("/closeFactory/ajax")
    @ResponseBody
    public Boolean deleteFactoryById(@RequestParam Long id){
        User user = (User) userReadService.findUserByUserId(id).getResult();
        user.setStatus(-1);
        Boolean isOk = (Boolean) userWriteService.update(user).getResult();
        return isOk;
    }

    /**
     * 启用管辖区域内指定的养殖场
     */
    @RequestMapping("/openFactory/ajax")
    @ResponseBody
    public Boolean openFactoryById(@RequestParam Long id){
        User user = (User) userReadService.findUserByUserId(id).getResult();
        user.setStatus(1);
        Boolean isOk = (Boolean) userWriteService.update(user).getResult();
        return isOk;
    }

    public Map getarea(HttpServletResponse response, HttpServletRequest request) {
        List<String> list = new ArrayList<>();
        list.add("province");
        list.add("city");
        list.add("region");
        list.add("street");
        list.add("village");
        Cookie[] cookies = null;
        cookies = request.getCookies();
        String name = "";
        Map map = new HashMap();
        for (Cookie cookie : cookies) {

            if (cookie.getName().equals("djtid")) {
                String id = cookie.getValue();
                int Id = Integer.parseInt(id);
                Response<User> userResponse = userReadService.findById(Integer.toUnsignedLong(Id));
                name = userResponse.getResult().getName();
                map.put("username", name);
                switch (userResponse.getResult().getAreaLevel()) {
                    case 1:
                        UserProfile userProfile = userProfileReadService.findUserProfileById(userResponse.getResult().getId()).getResult();
                        String Province = userProfile.getProvince();
                        Map map6 = new HashMap();
                        map6.put("province", Province);
                        List<BreedFactory> breedFactoryList = (List<BreedFactory>) breedFactoryReadService.findByArea(map6).getResult();
                        //获取所有省下城市

                        Map map1 = new HashMap();
                        map1.put("area1", list.get(1));
                        map1.put("area2", list.get(0));
                        map1.put("area3", Province);
                        List<String> citys = breedFactoryReadService.serachAllregion1(map1);
                        //获取城市下所有区
                        List<CityAreaDto> cityAreaDtoList = new ArrayList<>();
                        for (String city : citys) {
                            CityAreaDto cityAreaDto = new CityAreaDto();
                            Map map2 = new HashMap();
                            map2.put("area1", list.get(2));
                            map2.put("area2", list.get(1));
                            map2.put("area3", city);
                            List<String> regions = breedFactoryReadService.serachAllregion1(map2);
                            cityAreaDto.setCity(city);
                            cityAreaDto.setRegions(regions);
                            cityAreaDtoList.add(cityAreaDto);

                        }
                        map.put("userProfile", userProfile);
                        map.put("cityAreaDtoList", cityAreaDtoList);
                        map.put("breedFactorys", breedFactoryList);
                        //switch break;
                        break;
                    case 2:
                        UserProfile userProfile2 = userProfileReadService.findUserProfileById(userResponse.getResult().getId()).getResult();
                        String city1 = userProfile2.getCity();
                        Map map7 = new HashMap();
                        map7.put("city", city1);
                        List<BreedFactory> breedFactoryList1 = (List<BreedFactory>) breedFactoryReadService.findByArea(map7).getResult();
                        //获取所有省下城市

                        Map map21 = new HashMap();
                        map21.put("area1", list.get(2));
                        map21.put("area2", list.get(1));
                        map21.put("area3", city1);
                        List<String> citys2 = breedFactoryReadService.serachAllregion1(map21);
                        //获取城市下所有区
                        List<CityAreaDto> cityAreaDtoList1 = new ArrayList<>();
                        for (String city : citys2) {
                            CityAreaDto cityAreaDto = new CityAreaDto();
                            Map map2 = new HashMap();
                            map2.put("area1", list.get(3));
                            map2.put("area2", list.get(2));
                            map2.put("area3", city);
                            List<String> regions = breedFactoryReadService.serachAllregion1(map2);
                            cityAreaDto.setCity(city);
                            cityAreaDto.setRegions(regions);
                            cityAreaDtoList1.add(cityAreaDto);

                        }
                        map.put("userProfile", userProfile2);
                        map.put("cityAreaDtoList", cityAreaDtoList1);
                        map.put("breedFactorys", breedFactoryList1);
                        //switch break;
                        break;
                    case 3://区
                        UserProfile userProfile3 = userProfileReadService.findUserProfileById(userResponse.getResult().getId()).getResult();
                        String region = userProfile3.getRegion();
                        Map map36 = new HashMap();
                        map36.put("region", region);
                        List<BreedFactory> breedFactoryList3 = (List<BreedFactory>) breedFactoryReadService.findByArea(map36).getResult();
                        //获取所有区下城市镇

                        Map map31 = new HashMap();
                        map31.put("area1", list.get(3));
                        map31.put("area2", list.get(2));
                        map31.put("area3", region);
                        List<String> citys3 = breedFactoryReadService.serachAllregion1(map31);
                        //获取对应镇 对应村
                        List<CityAreaDto> cityAreaDtoList3 = new ArrayList<>();
                        for (String city : citys3) {
                            CityAreaDto cityAreaDto = new CityAreaDto();
                            Map map2 = new HashMap();
                            map2.put("area1", list.get(4));
                            map2.put("area2", list.get(3));
                            map2.put("area3", city);
                            List<String> regions = breedFactoryReadService.serachAllregion1(map2);
                            cityAreaDto.setCity(city);
                            cityAreaDto.setRegions(regions);
                            cityAreaDtoList3.add(cityAreaDto);

                        }
                        map.put("cityAreaDtoList", cityAreaDtoList3);
                        map.put("breedFactorys", breedFactoryList3);
                        map.put("userProfile", userProfile3);
                        //switch break;
                        break;
                    case 4://镇
                        UserProfile userProfile4 = userProfileReadService.findUserProfileById(userResponse.getResult().getId()).getResult();
                        String street = userProfile4.getStreet();
                        Map map46 = new HashMap();
                        map46.put("street", street);
                        List<BreedFactory> breedFactoryList4 = (List<BreedFactory>) breedFactoryReadService.findByArea(map46).getResult();
                        //获取所有镇下所有村

                        Map map41 = new HashMap();
                        map41.put("area1", list.get(4));
                        map41.put("area2", list.get(3));
                        map41.put("area3", street);
                        List<String> citys4 = breedFactoryReadService.serachAllregion1(map41);//所有村

                        List<CityAreaDto> cityAreaDtoList4 = new ArrayList<>();

                        CityAreaDto cityAreaDto = new CityAreaDto();

                        cityAreaDto.setCity(street);
                        cityAreaDto.setRegions(citys4);
                        cityAreaDtoList4.add(cityAreaDto);
                        map.put("userProfile", userProfile4);
                        map.put("cityAreaDtoList", cityAreaDtoList4);
                        map.put("breedFactorys", breedFactoryList4);
                        //switch break;
                        break;
                    case 5://村
                        UserProfile userProfile5 = userProfileReadService.findUserProfileById(userResponse.getResult().getId()).getResult();

                        List<GovernmentUserDuty> governmentUserDutyList = governmentUserDutyReadService.findGovernmentUserDutiesByUserId(userResponse.getResult().getId(), null).getResult();
                        List<Long> longlist = new ArrayList<>();
                        if (governmentUserDutyList.size()!=0){
                            for (GovernmentUserDuty governmentUserDuty : governmentUserDutyList) {
                                longlist.add(governmentUserDuty.getFactoryOrPointId());
                            }
                        }

                        List<String> villages = new ArrayList<>();
                        List<BreedFactory> breedFactoryList2 = breedFactoryReadService.findBreedFactoryDtoByIds(longlist).getResult();
                        for (BreedFactory breedFactory : breedFactoryList2) {
                            villages.add(breedFactory.getVillage());

                        }

                        List<String> listWithoutDup = new ArrayList<String>(new HashSet<String>(villages));


                        List<CityAreaDto> cityAreaDtoList5 = new ArrayList<>();

                        CityAreaDto cityAreaDto1 = new CityAreaDto();
                        cityAreaDto1.setCity(" ");

                        // cityAreaDto1.setCity(village);
                        cityAreaDto1.setRegions(listWithoutDup);

                        cityAreaDtoList5.add(cityAreaDto1);



                        map.put("cityAreaDtoList", cityAreaDtoList5);
                        map.put("breedFactorys", breedFactoryList2);
                        //switch break;
                        //switch break;
                        break;
                }


                break;
            }

        }

        return map;
    }


    public List findFactoryIdByArea(String region, int breedType) {

        Map map = new HashMap();
        if (breedType == -1) {
            map.put("breedType", null);
        } else {
            map.put("breedType", breedType);
        }
        List<String> list1 = new ArrayList<>();
        String[] list = region.split(",");

        for (int i = 0; i < list.length; i++) {
            list1.add(list[i]);
        }
        map.put("areas", list1);

        List<BreedFactory> breedFactoryList = (List<BreedFactory>) breedFactoryReadService.findByArea(map).getResult();

        return breedFactoryList;
    }


    @RequestMapping("ButcherFactoryList")
    private String ButcherFactory() {

        return "management/butcherfactory/ButcherFactoryList";
    }


}
